package org.obm.mina;

import java.io.IOException;

import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MinaIoHandler<T> implements IoHandler {
	private final MinaServer<T> server;

	private static final String MINA_HANDLER_ATTR = "MinaHandler";
	private static final Logger logger = LoggerFactory
			.getLogger(MinaIoHandler.class);

	MinaIoHandler(MinaServer<T> server) {
		this.server = server;
	}

	public void sessionCreated(IoSession session) throws IOException {
		session.setAttribute(MINA_HANDLER_ATTR, server.createHandler(session));
	}

	public void sessionOpened(IoSession session) throws IOException {
		getMinaHandler(session).connectionOpened();
	}

	public void sessionClosed(IoSession session) throws IOException {
		logger.info("session closed");
		getMinaHandler(session).connectionClosed();
	}

	public void sessionIdle(IoSession session, IdleStatus status)
			throws IOException {
		getMinaHandler(session).connectionIdle();
	}

	public void messageReceived(IoSession session, Object msg)
			throws IOException {
		getMinaHandler(session).messageReceived(msg);
	}

	public void exceptionCaught(IoSession session, Throwable e)
			throws IOException {
		logger.error(e.getMessage(), e);
		getMinaHandler(session).connectionClosed();
	}

	public void messageSent(IoSession session, Object msg) {
	}

	public static MinaHandler getMinaHandler(IoSession session) {
		return (MinaHandler) session.getAttribute(MINA_HANDLER_ATTR);
	}

}
